﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using DevExpress.Web;
using System.Threading;
using System.Globalization;
using log4net;
using Timesheet.Service;
using Timesheet.Common;
using Timesheet.Domain;

namespace Timesheet.WebForm
{
    public partial class Site : System.Web.UI.MasterPage
    {
        private readonly static ILog logger = LogManager.GetLogger("SiteMaster");
        
        //public string UserNameLabel { set { ASPxLblUserName.Text += value; } }

        public IUserService UserService { get; set; }

        public System.Web.UI.WebControls.Panel _MainPanel
        { 
            get { return MainPanel; }
        } 

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!this.Request.Url.ToString().Contains("Lines.aspx") && !this.Request.Url.ToString().Contains("report.aspx"))
                {
                    this.MainPanel.Width = 1099;
                }

                try
                {

                    if (Session["Username"] == null)
                    {
                        // *** Always force a signout when the page loads first
                        FormsAuthentication.SignOut();
                        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                        {
                            HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                            if (!string.IsNullOrEmpty(cookie.Value))
                            {
                                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                                string[] data = ticket.UserData.Split('|');
                                if (data.Length > 0)
                                {
                                    String encryptPassword = PasswordUtils.getHashPassword(data[1]);
                                    if (UserService.CheckAccountLogin(data[0], encryptPassword))
                                    {
                                        User info = UserService.GetByUsername(data[0]);
                                        Session["Username"] = info.Username;
                                        Session["UserId"] = info.Id;
                                        Session["User"] = info;
                                        Session["userrole"] = info.Manager ? "3":info.Coordinator ? "2" :info.TeamLead ? "1":"0";
                                        //ASPxLblUserName.Text += data[0];
                                        string ticketString = FormsAuthentication.Encrypt(ticket);
                                        cookie.Expires = DateTime.Now.AddDays(1);
                                        Response.Cookies.Clear();
                                        Response.Cookies.Add(cookie);
                                    }
                                    else
                                    {
                                        Response.Redirect("~/Account/Login.aspx?ReturnUrl=" +
                                                          Request.AppRelativeCurrentExecutionFilePath);
                                    }
                                }
                            }
                            else
                            {
                                Response.Redirect("~/Account/Login.aspx?ReturnUrl=" +
                                                  Request.AppRelativeCurrentExecutionFilePath);
                            }
                        }
                        else
                        {
                            Response.Redirect("~/Account/Login.aspx?ReturnUrl=" +
                                              Request.AppRelativeCurrentExecutionFilePath);
                        }
                    }
                    else
                    {
                        //ASPxLblUserName.Text = "Welcome " + Session["Username"].ToString();
                    }
                }catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    ASPxWebControl.RedirectOnCallback("~/Account/Login.aspx?ReturnUrl=" + Request.AppRelativeCurrentExecutionFilePath);
                }
            }
            else
            {

                if (Session["UserId"] == null)
                {
                    try
                    {
                        Response.Redirect("~/Account/Login.aspx?ReturnUrl=" + Request.AppRelativeCurrentExecutionFilePath);
                    }
                    catch (Exception)
                    {
                        ASPxWebControl.RedirectOnCallback("~/Account/Login.aspx?ReturnUrl=" + Request.AppRelativeCurrentExecutionFilePath);
                    }
                  
                }
            }
           
        }

        
    }
}
